<template>
  <div style="width: 75%;margin: 0 auto">
    <el-card>
      <el-tabs v-model="searchForm.status" @tab-change="getPageList">
        <el-tab-pane label="全部" name=""></el-tab-pane>
        <el-tab-pane label="待付款" name="1"></el-tab-pane>
        <el-tab-pane label="待发货" name="2"></el-tab-pane>
        <el-tab-pane label="待收货" name="3"></el-tab-pane>
        <el-tab-pane label="待评价" name="4"></el-tab-pane>
        <el-tab-pane label="已完成" name="5"></el-tab-pane>
        <el-tab-pane label="已取消" name="6"></el-tab-pane>
      </el-tabs>
      <el-space direction="vertical" alignment="left" style="width: 100%">
        <el-table ref="tableComponents"
                  :data="listData"
                  tooltip-effect="dark"
                  style="width: 100%"
                  border>
          <el-table-column prop="orderId" label="订单ID" width="80"></el-table-column>
          <el-table-column prop="name" label="商品名称" ></el-table-column>
          <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <el-image style="width: 80px; height: 80px;" :src="scope.row.mainImg" fit="cover" />
            </template>
          </el-table-column>
          <el-table-column prop="number" label="数量"></el-table-column>
          <el-table-column prop="sum" label="金额"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <!-- 1，待付款  2，待发货  3，待收货  4，待评价  5，完成  6，取消 -->
              <el-tag v-if="scope.row.itemStatus===1" type="warning">待付款</el-tag>
              <el-tag v-else-if="scope.row.itemStatus===2" type="info">待发货</el-tag>
              <el-tag v-else-if="scope.row.itemStatus===3" type="primary">待收货</el-tag>
              <el-tag v-else-if="scope.row.itemStatus===4" type="success">待评价</el-tag>
              <el-tag v-else-if="scope.row.itemStatus===5" type="success">已完成</el-tag>
              <el-tag v-else-if="scope.row.itemStatus===6" type="danger">已取消</el-tag>
              <el-tag v-else-if="scope.row.itemStatus" :type="getStatusTagType(scope.row.itemStatus)">{{ getStatusText(scope.row.itemStatus) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="uname" label="收货人姓名"></el-table-column>
          <el-table-column prop="tel" label="收货人电话"></el-table-column>
          <el-table-column prop="address" label="收货人地址" show-overflow-tooltip></el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createDate" label="创建时间" width="180"></el-table-column>
          <el-table-column fixed="right" label="操作" width="160">
            <template #default="scope">
              <!-- 待付款状态 - 可以付款或取消 -->
              <el-button type="primary" link v-if="scope.row.itemStatus===1" @click="pay(scope.row)">
                付款
              </el-button>
              <el-popconfirm title="确认取消订单吗?" @confirm="cancel(scope.row)">
                <template #reference>
                  <el-button link type="danger" v-if="scope.row.itemStatus===1">
                    取消
                  </el-button>
                </template>
              </el-popconfirm>
              
              <!-- 待收货状态 - 可以确认收货 -->
              <el-popconfirm title="确认收货后钱会打款给卖家，是否继续?" @confirm="confirm(scope.row)">
                <template #reference>
                  <el-button link type="success" v-if="scope.row.itemStatus===3 || scope.row.itemStatus===3">
                    确认收货
                  </el-button>
                </template>
              </el-popconfirm>
              
              <!-- 待评价状态 - 可以评价 -->
              <el-button type="primary" link v-if="scope.row.itemStatus===4 || scope.row.itemStatus===4" @click="showAddEvaluate(scope.row)">
                写评价
              </el-button>
              
              <!-- 已评价订单 - 可以查看评价 -->
              <el-button type="success" link v-if="scope.row.orderEvaluateId" @click="showEvaluate(scope.row)">
                查看评价
              </el-button>
              
              <!-- 订单详情按钮 - 所有状态都可以查看 -->
              <el-button type="info" link @click="showOrderDetails(scope.row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
          <el-pagination
              @current-change="currentChange"
              @size-change="sizeChange"
              :page-size="pageInfo.pageSize"
              :current-page="pageInfo.pageNum"
              background
              layout="total,sizes, prev, pager, next"
              :total="pageInfo.total">
          </el-pagination>
        </div>
      </el-space>
    </el-card>
  </div>

  <!-- 订单详情对话框 -->
  <el-dialog
      v-model="orderDetailsVisible"
      title="订单详情"
      width="600px"
  >
    <el-descriptions :column="1" border>
      <el-descriptions-item label="订单ID">{{ selectedOrder.orderId }}</el-descriptions-item>
      <el-descriptions-item label="商品名称">{{ selectedOrder.name }}</el-descriptions-item>
      <el-descriptions-item label="订单状态">
        <el-tag v-if="selectedOrder.status===1" type="warning">待付款</el-tag>
        <el-tag v-else-if="selectedOrder.status===2" type="info">待发货</el-tag>
        <el-tag v-else-if="selectedOrder.status===3" type="primary">待收货</el-tag>
        <el-tag v-else-if="selectedOrder.status===4" type="success">待评价</el-tag>
        <el-tag v-else-if="selectedOrder.status===5" type="success">已完成</el-tag>
        <el-tag v-else-if="selectedOrder.status===6" type="danger">已取消</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="商品状态" v-if="selectedOrder.item_status">
        <el-tag :type="getStatusTagType(selectedOrder.item_status)">
          {{ getStatusText(selectedOrder.item_status) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="数量">{{ selectedOrder.number }}</el-descriptions-item>
      <el-descriptions-item label="金额">{{ selectedOrder.sum }}</el-descriptions-item>
      <el-descriptions-item label="收货人姓名">{{ selectedOrder.name }}</el-descriptions-item>
      <el-descriptions-item label="收货人电话">{{ selectedOrder.tel }}</el-descriptions-item>
      <el-descriptions-item label="收货地址">{{ selectedOrder.address }}</el-descriptions-item>
      <el-descriptions-item label="备注">{{ selectedOrder.remark || '无' }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ selectedOrder.createDate }}</el-descriptions-item>
    </el-descriptions>
  </el-dialog>

  <!-- 评价对话框 -->
  <el-dialog
      v-model="productOrderEvaluateDialogVisible"
      :title="productOrderEvaluate.id ? '评价详情' : '添加评价'"
      width="500"
  >
    <template v-if="!productOrderEvaluate.id">
      <el-form :model="productOrderEvaluate" label-width="80px">
        <el-form-item label="评分">
          <el-rate
              v-model="productOrderEvaluate.rate"
              show-score
              text-color="#ff9900"
              score-template="{value} 分"
          />
        </el-form-item>
        <el-form-item label="详细内容">
          <el-input v-model="productOrderEvaluate.content" type="textarea" :rows="4"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addEvaluate">提交</el-button>
          <el-button @click="productOrderEvaluateDialogVisible=false">取消</el-button>
        </el-form-item>
      </el-form>
    </template>
    
    <template v-else>
      <el-descriptions title="" column="1">
        <el-descriptions-item label="评分">
          <el-rate
              v-model="productOrderEvaluate.rate"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value} 分"
          />
        </el-descriptions-item>
        <el-descriptions-item label="详细内容">{{ productOrderEvaluate.content }}</el-descriptions-item>
        <el-descriptions-item label="评价时间">{{ productOrderEvaluate.createTime }}</el-descriptions-item>
      </el-descriptions>
    </template>
  </el-dialog>
</template>

<script setup>
import request from "@/utils/http.js";
import {Check, Close, Delete, Edit, Refresh, Plus, Search} from '@element-plus/icons-vue'
import {ref, toRaw} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";

const tableComponents = ref();
const listData = ref([]);
const pageInfo = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const searchForm = ref({
  status: ""
});

// 订单详情相关
const orderDetailsVisible = ref(false);
const selectedOrder = ref({});

const router = useRouter();

getPageList()

/**
 * 获取分页数据
 */
function getPageList() {
  let data = Object.assign(toRaw(searchForm.value), toRaw(pageInfo.value))
  // Add qwe=1 parameter to indicate frontend
  data.qwe = 1;
  
  listData.value = []; // Clear previous data
  request.get("/api/productOrder/page", {
    params: data
  }).then(res => {
    if (res.code === 1) {
      const ltd = res.data.list;
      console.log(ltd)
      for(let i=0; i<ltd.length; i++){
        for(let j=0; j<ltd[i].productRts.length; j++){
          let x = ltd[i].productRts[j];
          x.address = ltd[i].address;
          x.uname = ltd[i].name;
          x.tel = ltd[i].tel;
          x.status = ltd[i].status; // order status
          x.createDate = ltd[i].createDate;
          x.orderId = ltd[i].oid;
          x.trackingNumber = ltd[i].trackingNumber;
          x.remark = ltd[i].userMessage;
          x.orderEvaluateId = ltd[i].orderEvaluateId;
          listData.value.push(x);
        }
      }

      pageInfo.value.total = res.data.total;
    } else {
      ElMessage.error(res.msg || "获取订单列表失败");
    }
  }).catch(error => {
    ElMessage.error("获取订单列表失败: " + error.message);
  });
}

/**
 * 选择分页
 * @param e
 */
function currentChange(e) {
  pageInfo.value.pageNum = e
  getPageList()
}

/**
 * 改变分页数量
 * @param e
 */
function sizeChange(e) {
  pageInfo.value.pageSize = e
  getPageList()
}

/**
 * 支付订单
 */
function pay(row) {
  // 重定向到支付页面，传递订单ID
  router.push(`/payment/${row.orderId}`);
}

/**
 * 取消订单
 */
function cancel(row) {
  request.post("/api/productOrder/cancel/" + row.orderId).then(res => {
    if (res.code === 1) {
      ElMessage({
        message: "订单已取消",
        type: 'success'
      });
      getPageList();
    } else {
      ElMessage.error(res.msg || "取消订单失败");
    }
  }).catch(error => {
    ElMessage.error("取消订单失败: " + error.message);
  });
}

const productOrderEvaluateDialogVisible = ref(false)
const productOrderEvaluate = ref({})

/**
 * 显示添加评价对话框
 */
function showAddEvaluate(row) {
  productOrderEvaluate.value = {
    productOrderId: row.orderId,
    productId: row.id,
    rate: 5
  }
  productOrderEvaluateDialogVisible.value = true
}

/**
 * 添加评价
 */
function addEvaluate() {
  if (!productOrderEvaluate.value.content) {
    ElMessage.warning("请输入评价内容");
    return;
  }
  
  request.post("/api/productOrderEvaluate/add", productOrderEvaluate.value).then(res => {
    if (res.code === 1) {
      productOrderEvaluateDialogVisible.value = false
      ElMessage({
        message: "评价成功",
        type: 'success'
      });
      getPageList()
    } else {
      ElMessage.error(res.msg || "评价失败");
    }
  }).catch(error => {
    ElMessage.error("评价失败: " + error.message);
  });
}

/**
 * 显示评价详情
 */
function showEvaluate(row) {
  request.get("/api/productOrderEvaluate/selectById/" + row.orderEvaluateId).then(res => {
    if (res.code === 1) {
      productOrderEvaluate.value = res.data;
      productOrderEvaluateDialogVisible.value = true;
    } else {
      ElMessage.error(res.msg || "获取评价失败");
    }
  }).catch(error => {
    ElMessage.error("获取评价失败: " + error.message);
  });
}

function showOrderDetails(row) {
  selectedOrder.value = {...row};
  orderDetailsVisible.value = true;
}

/**
 * 获取状态文本
 */
function getStatusText(status) {
  switch (parseInt(status)) {
    case 1: return '待付款';
    case 2: return '待发货';
    case 3: return '待收货';
    case 4: return '待评价';
    case 5: return '已完成';
    case 6: return '已取消';
    default: return '未知状态';
  }
}

/**
 * 获取状态标签类型
 */
function getStatusTagType(status) {
  switch (parseInt(status)) {
    case 1: return 'warning';
    case 2: return 'info';
    case 3: return 'primary';
    case 4: return 'success';
    case 5: return 'success';
    case 6: return 'danger';
    default: return 'info';
  }
}

/**
 * 确认收货
 */
function confirm(row) {
  const data = {
    oid: row.orderId,
    pid: row.id
  };
  
  request.post("/api/productOrder/confirm", data).then(res => {
    if (res.code === 1) {
      ElMessage({
        message: "确认收货成功",
        type: 'success'
      });
      getPageList();
    } else {
      ElMessage.error(res.msg || "确认收货失败");
    }
  }).catch(error => {
    ElMessage.error("确认收货失败: " + error.message);
  });
}

</script>

<style scoped>
.el-image {
  border-radius: 4px;
}

.el-table {
  --el-table-border-color: #EBEEF5;
}

.el-descriptions {
  margin: 20px 0;
}

.el-descriptions-item {
  padding: 12px 16px;
}

/* Add table row height limit */
:deep(.el-table__row) {
  max-height: 80px;
}

:deep(.el-table .cell) {
  max-height: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.5;
}
</style>
